<?php
class Admin_Model_Product extends Zend_Db_Table_Abstract
{
	protected $_name="product";
	protected $_errorList = array();
	
	public function getErrorMsg()
	{
		return $this->_errorList;
	}
	public function getPublishedProducts($num)
	{
		$db=Zend_Registry::get('connectDB');		
		$select=$db->select()->from($this->_name);
		$select->where('product.status = 1');
		//$langId = My_Translate::getLanguage();
		//$select->where('product_category.languageId = '.$langId);
		$select->joinLeft('product_category', 
					'product_category.categoryId=product.categoryId', array('categoryName'));
		$select->joinLeft('user', 
					'user.userId=product.createdBy', array('userName'));
		$select->order("productID ASC")->limit($num);
		return $select->query()->fetchAll();
		
	}
	public function getCategoryProducts($categoryId,$currentpage,$size=20)
	{
		$db=Zend_Registry::get('connectDB');		
		$select=$db->select()->from($this->_name);
		///if($categoryId>0)
		$select->where('product.categoryId ='.$categoryId);
		//$langId = My_Translate::getLanguage();
		//$select->where('product_category.languageId = '.$langId);
		$select->joinLeft('product_category', 
					'product_category.categoryId=product.categoryId', array('categoryName'));
		$select->joinLeft('user', 
					'user.userId=product.createdBy', array('userName'));
		//$select->order("productID ASC")->limit($num);
		//return $select->query()->fetchAll();
		if(!empty($size))
    	{
	    	Zend_Paginator::setDefaultScrollingStyle('Sliding');
			Zend_View_Helper_PaginationControl
				::setDefaultViewPartial('partials/paginator.phtml');
	    	$paginator = Zend_Paginator::factory($select);
	    	//if(isset($_GET['page']))
	    	//{
	    		$page = $currentpage;	    		
	    		//$page=2;
	    		///$page = $this->getParam('page');
	    	//}
	    	//else {
	    		//$page =0;
	    	//}
	    	//$page = $_GET['page'];
			$paginator->setCurrentPageNumber($page);
			$paginator->setItemCountPerPage($size);
			$data= $paginator;
			$this->_actionController->view->paginator = $paginator;
			//echo $paginator;
    	}
    	else{
    		if($select instanceof Zend_Db_Select)
    		{
    			$data = $select->query()->fetchAll();	
    		}
    		//$this->_actionController->view->data = $data;
    	}
    	$arr=array("data"=>$data,"paginator"=>$paginator);
    	return $arr;
		
	}
	public function getOneProduct($id)
	{
		$db=Zend_Registry::get('connectDB');
		$select=$db->select()->from($this->_name);
		$select->where("product.productId = $id");
		
		$select->joinLeft('product_category', 
					'product_category.categoryId=product.categoryId', array('categoryName'));
		$select->joinLeft('user', 
					'user.userId=product.createdBy', array('userName'));
		
		return $select->query()->fetchAll();
		
	}
	public function getRowProduct($id)
	{
		$db=Zend_Registry::get('connectDB');
		$select=$db->select()->from($this->_name);
		$select->where("product.productId = $id");
		
		$select->joinLeft('product_category', 
					'product_category.categoryId=product.categoryId', array('categoryName'));
		$select->joinLeft('user', 
					'user.userId=product.createdBy', array('userName'));
		
		return $db->fetchRow($select);
		
	}
	public function getRandomProducts($currentpage,$size=20)
	{
		$db=Zend_Registry::get('connectDB');
		$select=$db->select()->from($this->_name);
		//$select->where('product.status = 1');
		//$langId = My_Translate::getLanguage();
		//$select->where('product_category.languageId = '.$langId);
		$select->joinLeft('product_category', 
					'product_category.categoryId=product.categoryId', array('categoryName'));
		$select->joinLeft('user', 
					'user.userId=product.createdBy', array('userName'));
		//$select->order("productID ASC")->limit($num);
		$select->order("productID ASC");
		//$data=$select->query()->fetchAll();		
		
	if(!empty($size))
    	{
	    	Zend_Paginator::setDefaultScrollingStyle('Sliding');
			Zend_View_Helper_PaginationControl
				::setDefaultViewPartial('partials/paginator.phtml');
	    	$paginator = Zend_Paginator::factory($select);
	    	//if(isset($_GET['page']))
	    	//{
	    		$page = $currentpage;	    		
	    		//$page=2;
	    		///$page = $this->getParam('page');
	    	//}
	    	//else {
	    		//$page =0;
	    	//}
	    	//$page = $_GET['page'];
			$paginator->setCurrentPageNumber($page);
			$paginator->setItemCountPerPage($size);
			$data= $paginator;
			$this->_actionController->view->paginator = $paginator;
			//echo $paginator;
    	}
    	else{
    		if($select instanceof Zend_Db_Select)
    		{
    			$data = $select->query()->fetchAll();	
    		}
    		//$this->_actionController->view->data = $data;
    	}
    	$arr=array("data"=>$data,"paginator"=>$paginator);
    	return $arr;
		
	}
	public function UpdateProduct($product)
	{
		$data=$this->bind();
		$rowProduct = $this->find($data['productId'])->current();		
		if(count($rowProduct)>0) {
	        // update the row values
	       $rowProduct->productName = $data['productName'];
	        $rowProduct->summary =  $data['summary'];
	        $rowProduct->description =  $data['description'];
	       $rowProduct->categoryId = $data['categoryId'];
	       $rowProduct->status = $data['status'];
	       $rowProduct->imageURL = $data['imageURL'];
	        $rowProduct->creationTime = $data['creationTime'];
	         $rowProduct->createdBy = $data['createdBy'];
	         $rowProduct->ordering = $data['ordering'];
	         
	        $rowProduct->save();
	        //return the updated user	        
	        return true;
	    }else{
	        return false;
	    }
	}
	public function publish($col = "status")
	{
		//if (!My_Db::checkColumnExist ( $this->getTable(), "status" )) {
			//return self::buildData ( );
		//}		
		$params = explode(";",$_POST['params']);
		$status = $params[0];
		$id = $params[1];
		$status = !($status);
		
		if(!empty($col) && !empty($id))
		{
			$rowProduct = $this->find($id)->current();
			if($rowProduct)
			{
				$rowProduct[$col] = $status;
				$rowProduct->save();
			}
		}
		
	}
	
	public function SaveOrder($col="ordering")
	{
		$db=Zend_Registry::get('connectDB');
		
		$items = explode ( ";", $_POST ['params'] );			
			foreach ( $items as $item ) {
				$info = explode ( ",", $item );
				$id = $info[0];
				$order = $info[1]; 
				if(!empty($col) && !empty($id))
				{
					$rowProduct = $this->find($id)->current();
					$rowProduct->ordering=$order;			
					$rowProduct->save();
				}
		}
	}
	public function CreateProduct()
	{
		if(!$this->check())
    	{
			return false;
    	}
	// create a new row
        $rowProduct = $this->bind();
        if ($rowProduct) {         
                        
            $rowProduct->save();           
            return $rowProduct;
        } else {
            throw new Zend_Exception("Could not create user! ");
        }
	}
	public function DeleteProduct($id)
	{
		$rowProduct = $this->find($id)->current();		
		if($rowProduct) {	     	       
	        $rowProduct->delete();	        
	        return true;
	    }else{
	        return false;
	    }
	}
	
	public function DeleteMoreProduct()
	{
				$box=$_POST['chkBox'];
				while (list ($key,$val) = @each ($box)) { 
				$this->DeleteProduct($val);
				} 
				return true;
	}
	public static function createThumb($fileName,$new_w,$new_h)
	{
		$ext=end(explode('.',$fileName));
		if (preg_match('/jpg|jpeg/',$ext)){
			$src_img=imagecreatefromjpeg($fileName);
		}
		if (preg_match('/png/',$ext)){
			$src_img=imagecreatefrompng($fileName);
		}
		$old_x=imageSX($src_img);
		$old_y=imageSY($src_img);
		if($old_x <= $new_w || $old_y <= $new_h)
		{
			return false;
		}
		if ($old_x > $old_y) {
			$thumb_w=$new_w;
			$thumb_h=$old_y*($new_h/$old_x);
		}
		if ($old_x < $old_y) {
			$thumb_w=$old_x*($new_w/$old_y);
			$thumb_h=$new_h;
		}
		if ($old_x == $old_y) {
			$thumb_w=$new_w;
			$thumb_h=$new_h;
		}
		$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
		imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
		$thumbFile = "thumb_".basename($fileName);
		
		if (preg_match("/png/",$ext))
		{
			imagepng($dst_img,dirname($fileName)."/".$thumbFile);
		} else {
			imagejpeg($dst_img,dirname($fileName)."/".$thumbFile);
		}
		imagedestroy($dst_img);
		imagedestroy($src_img);
		return $thumbFile;
	}
	public function bind()
	{
		$product = $this->createRow();
		if(!empty($_POST['productId']))//case edit
		{
			$product->productId = $_POST['productId'];
		}		
		$product->productName = $_POST['productName'];
		$product->summary = $_POST['summary'];
		$product->description = $_POST['description'];
		$product->status = $_POST['status'];
		$product->categoryId = $_POST['categoryId'];
		if(!empty($_POST['createdBy']))
		{
			$product->createdBy = $_POST['createdBy'];
		}
		else {
			$product->createdBy = 2;
		}
		$product->ordering=$_POST['ordering'];
		
		if(!empty($_POST['creationTime']))
		{
			$product->creationTime=$_POST['creationTime'];
		}
		else {
			$product->creationTime = date ( "Y-m-d h:i:s" );
		}
		
		//Case insert product
		if(empty($_POST['productId']))//case insert
		{
			$product->creationTime = date ( "Y-m-d h:i:s" );
			$product->createdBy = 2;
			$product->ordering = 1;
		}
		
		if (! empty ( $_POST ['imageURL']['name'] )) 
		{
			if(!empty($_POST['productId']))//case edit, remove old images
			{
				$uploadDir = PRODUCT_IMG_UPLOAD_PATH;
				$imgFile = $uploadDir.$product->imageURL;
				$thumbFile = $uploadDir.$product->thumbnailURL;
				@unlink($imgFile);
				@unlink($thumbFile);	
			}
			
			$product->imageURL = basename ( $_POST ['imageURL'] ['name'] );
			$uploadDir = PRODUCT_IMG_UPLOAD_PATH;
			$product->thumbnailURL = $this->createThumb ( $uploadDir . $product->imageURL, 99, 99 );
			
		}
		
		return $product;
	}
	public function check()
    {
		//validate Product Name
		$titleVald = new Zend_Validate_StringLength(3, 255);
		if(!$titleVald->isValid($_POST['productName']))
		{
			$this->_errorList["productName"] = "S002|productName|10|255";
			return false;
		}
		
		//validate Summary
		$summaryVald = new Zend_Validate_StringLength(5);
		if(!$summaryVald->isValid($_POST['summary']))
		{
			$this->_errorList["summary"] = "S003|Summary|5";
			return false;
		}
		
		//validate category
		if(empty($_POST['categoryId']))
		{
			$this->_errorList["categoryId"] = "S001|Category";
		}
		
		//validate description
		$bodyVald = new Zend_Validate_StringLength(10);
		if(!$bodyVald->isValid($_POST['description']))
		{
			$this->_errorList["description"] = "S003|Description|10";
		}
		
		//validate image
		if(!empty($_FILES['imageURL']['name']))
		{
			$adapter = new Zend_File_Transfer_Adapter_Http();

			$adapter->addValidator('IsImage', false);
			if(!$adapter->isValid())
			{
				$this->_errorList["imageURL"] = "S004";
				return false;
			}

			$uploadDir = PRODUCT_IMG_UPLOAD_PATH;
			if(!is_readable($uploadDir))
			{
				$this->_errorList["imageURL"] = "Thư mục upload trên server ko tồn tại!";
				return false;
			}
			$rand = date("Ymdhis").rand()."_";
			$fileName = $rand.$_FILES ['imageURL']['name'];
			$res = move_uploaded_file($_FILES ['imageURL']['tmp_name'],$uploadDir."/".$fileName);
			if (! $res) {
				$this->_errorList["imageURL"] = "Không thể upload file này!";
				return false;
			}
			$_POST['imageURL']['name'] = $fileName;
		}
		
		if(empty($this->_errorList) == false)
		{
			return false;
		}
		return true;
    }
}